import axios from "axios";
import { message } from "ant-design-vue";
import router from "../router";
const service = axios.create({
  baseURL: "/seller",
  timeout: 5000
});
//请求拦截器
service.interceptors.request.use(
  config => {
    config.headers["X-Requested-With"] = "XMLHttpRequest";
    return config;
  },
  error => {
    console.log(error); //For debug
    Promise.reject(error);
  }
);
service.interceptors.response.use(
  response => {
    response.data.code = response.data.code * 1;
    let code = response.data.code;
    let msg = response.data.msg;
    switch (code) {
      case 1:
        if (msg) {
          message.success(msg);
        }
        break;
      case -1:
        message.error(msg);
        break;
    }
    return response.data;
  },
  error => {
    let response = error.response;
    let status = response.status;
    let config = error.config;
    let msg = "";
    switch (status) {
      case 404:
        msg = response.data.msg || "请求地址不存在";
        message.error(msg);
        break;
      case 419:
        //令牌过期重新获取
        config.baseURL = "";
        axios.get("/seller/csrf").then(() => {
          axios(config);
        });
        break;
      case 405:
        message.error("请求方式不存在");
        break;
      case 401:
        message.error("请先登录");
        router.replace("/login");
        break;
      case 422:
        var $data = response.data.data;
        var fields = {};
        fields[$data.field] = {
          errors: [
            {
              message: $data.msg,
              field: $data.field
            }
          ]
        };
        error.errorBag = fields;
        break;
      case 500:
        message.error("服务器异常");
        if (process.env.NODE_ENV === "development") {
          console.log(response.data.exception);
        }
        break;
    }
    return Promise.reject(error);
  }
);
export default service;
